package com.wsl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.junit.Test;

import java.util.Calendar;
import java.util.HashMap;

/**
 * @Author: MI
 * @Date: 2021/8/23/22:25
 * @Description:
 */
public class JwtDemo {

    @Test
    public void create() {
        creates();

    }

private String creates() {
    HashMap<String, Object> map = new HashMap<>();
    Calendar instance = Calendar.getInstance();
    instance.add(Calendar.SECOND, 1000);
    String sign = JWT.create()
            .withHeader(map)//设置header
            .withClaim("userId", 21)//payload
            .withClaim("userName", "xiaochen")
            .withExpiresAt(instance.getTime())//指定令牌过期时间
            .sign(Algorithm.HMAC256("12wsdfw~!@#"));//签名
    return sign;
}

@Test
public void test() {
    String token = creates();
    //先验证签名
    JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("12wsdfw~!@#")).build();
    DecodedJWT verify = jwtVerifier.verify(token);
    String userName = verify.getClaim("userName").asString();
    System.out.println(userName);
    System.out.println(verify.getClaim("userId").asInt());
}
}
